package CouponService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/CouponReq"
	"gdshop-back-end-go/client-api/app/response/CouponResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/response"
)

func GetWhereText(typeStr int) string {
	switch typeStr {
	case 3: // 已过期
		return " AND mc.expires_time<unix_timestamp()"
	case 2: // 已使用
		return " AND mc.use_time>0"
	case 1: // 未使用，未过期
		return " AND mc.use_time<1 AND mc.expires_time>unix_timestamp()"
	}

	return ""
}

func My(ctx context.Context, parames *CouponReq.My) *response.JsonResponse {
	var res []*CouponResp.Index
	err := toolsDb.GetUnSafaTable(ctx, "coupon").As("c").
		LeftJoin("member_coupon AS mc", "mc.coupon_id = c.id").Fields("c.*").
		Where("c.delete_at<1 AND mc.delete_at<1 AND mc.member_id = ? "+GetWhereText(parames.Type), parames.MemberId).Structs(&res)

	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessageData(nil, "成功", res)
}

// GetMyCouponNum 我的优惠券数量
func GetMyCouponNum(ctx context.Context, memberId int) int {
	count, err := toolsDb.GetUnSafaTable(ctx, "coupon").As("c").
		LeftJoin("member_coupon AS mc", "mc.coupon_id = c.id").Fields("1").
		Where("c.delete_at<1 AND mc.delete_at<1 AND mc.member_id = ? "+GetWhereText(1), memberId).Count()
	if err != nil {
		return 0
	}

	return count
}
